#include "ic.h"
#include "key.h"
#include "string.h"
#include "stdio.h"

IC_FLAGS ic_flags = {0};
IC_COUNTERS ic_counters = {0};
TIM_HandleTypeDef ic_handle = {0};

void ic_init(uint16_t arr, uint16_t psc)
{
    TIM_IC_InitTypeDef ic_config = {0};
    
    ic_handle.Instance = TIM2;
    ic_handle.Init.Prescaler = psc;
    ic_handle.Init.Period = arr;
    ic_handle.Init.CounterMode = TIM_COUNTERMODE_UP;
    ic_handle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
    
    ic_config.ICPrescaler = TIM_ICPSC_DIV1;
    ic_config.ICPolarity = TIM_ICPOLARITY_FALLING;
    ic_config.ICSelection = TIM_ICSELECTION_DIRECTTI;
    ic_config.ICFilter = 0x0;
    
    HAL_TIM_IC_Init(&ic_handle);
    HAL_TIM_IC_ConfigChannel(&ic_handle, &ic_config, TIM_CHANNEL_2);
    __HAL_TIM_ENABLE_IT(&ic_handle, TIM_IT_UPDATE);
    HAL_TIM_IC_Start_IT(&ic_handle, TIM_CHANNEL_2);
}

void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim)
{
    if (htim->Instance != TIM2)
        return ;
    
    __HAL_RCC_TIM2_CLK_ENABLE();
    key_init();
    
    HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_2);
    HAL_NVIC_SetPriority(TIM2_IRQn, 2, 1);
    HAL_NVIC_EnableIRQ(TIM2_IRQn);
}

void TIM2_IRQHandler(void)
{
    HAL_TIM_IRQHandler(&ic_handle);
}
    

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    if (htim->Instance != TIM2)
        return ;
    
    if ((!ic_flags.IC_FALLING_FLAG) || ic_flags.IC_SUCCESS_FLAG)
        return ;
    
    ic_counters.TIMx_TIMEOUT_COUNTER++;
//    printf("cycle is : %d\r\n", ic_counters.TIMx_TIMEOUT_COUNTER);
}

void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
    if (ic_flags.IC_SUCCESS_FLAG) return ;
    
    if (ic_flags.IC_FALLING_FLAG)
    {
        ic_flags.IC_RISING_FLAG = 1;
        ic_flags.IC_SUCCESS_FLAG = 1;
         ic_counters.IC_RISING_COUNTER = __HAL_TIM_GET_COUNTER(htim);
        __HAL_TIM_SET_CAPTUREPOLARITY(htim, TIM_CHANNEL_2, TIM_INPUTCHANNELPOLARITY_FALLING);
        printf("press up\r\n");
    }else
    {
        ic_flags.IC_FALLING_FLAG = 1;
//        __HAL_TIM_DISABLE(htim);
        ic_counters.IC_FALLINF_COUNTER = __HAL_TIM_GET_COUNTER(htim);
        __HAL_TIM_SET_COUNTER(htim, 0);
        __HAL_TIM_SET_CAPTUREPOLARITY(htim, TIM_CHANNEL_2, TIM_INPUTCHANNELPOLARITY_RISING);
//        __HAL_TIM_ENABLE(htim);
        printf("press down\r\n");
    }
}

uint32_t ic_time_get(void)
{
    if (!ic_flags.IC_SUCCESS_FLAG) return 0;
    
    uint32_t total_time = 0;
    memset(&ic_flags, 0, sizeof(ic_flags));
    total_time = ic_counters.TIMx_TIMEOUT_COUNTER * 65536 + ic_counters.IC_RISING_COUNTER;
    memset(&ic_counters, 0, sizeof(ic_counters));
    
    printf("time is : %d us \r\n", total_time);
    
    return total_time;
}
